package com.luis.toolbox.common;

import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Constants {

	public static final String LINE_REGEXP=".*item_code=(.*) value=(.*) (\\d+)";
	public static final int EQUIP_START_POS=2;
	public static final int EQUIP_END_POS=20;
	
	public enum ThingType{
		DEVICE("Device"),
		GATEWAY("Gateway");
		private final String type;
		ThingType(String t) {
			this.type = t;
		}
		public String getType() {
			return type;
		}
	}
	
	public static String[] parseLine(String line) {
		Pattern r = Pattern.compile(LINE_REGEXP);
		Matcher m = r.matcher(line);
		
		if(m.find()) {
			return new String[] {m.group(1),m.group(2),m.group(3)};
		}
		return null;
	}

	/**
	 * 将line protocol的数据按照设备进行解析分类
	 * @param lineData post的报文，一行表示一条数据
	 * @return Map<k,v> k表示设备编码，对应云端设备标识，v是相应设备的数据集合
	 * */
	public static Map<String, List<String>> mapToEquip(String lineData) {
		String[] lines = lineData.split(System.lineSeparator());
		Map<String,List<String>> equipDataMap = new HashMap<>();
		for(String line : lines) {
			String[] parseResult = Constants.parseLine(line);
			if(parseResult == null) continue;
			String equipCode = parseResult[0].substring(Constants.EQUIP_START_POS,Constants.EQUIP_END_POS);
			equipDataMap.computeIfAbsent(equipCode, k -> new ArrayList<>()).add(line);
		}
		return equipDataMap;
	}

	public static String handleCompanyCode(String payload, String companyCode){
		String[] lines = payload.split("\\r\\n|\\n");
		return Arrays.stream(lines).map(line->{
			String[] result = Constants.parseLine(line);
			if(result !=null && result[0].startsWith(companyCode))
				return line.replaceFirst(companyCode+"_", "");
			return line;
		}).collect(Collectors.joining(System.lineSeparator()));
	}

	public static <T> List<T> doSampling(List<T> targetItem, int sampleCount){
		if(CollectionUtils.isEmpty(targetItem)) return Collections.emptyList();
		if(targetItem.size() < sampleCount) return targetItem;
		Collections.shuffle(targetItem);
		return targetItem.subList(0,sampleCount);
	}
}
